﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using MongoDB.Driver;
using MongoManager.Tests.Entities;

namespace MongoManager.Tests.Converters
{
    public class UserToDocumentConverter : ITypeConverter<User, Document>
    {

        public Document Convert(User source)
        {
            Document newDocument = new Document();

            if (!string.IsNullOrEmpty(source.ID))
                newDocument["_id"] = new Oid(source.ID);

            if (!string.IsNullOrEmpty(source.UserName))
                newDocument["UserName"] = source.UserName;

            if (!string.IsNullOrEmpty(source.EmailAddress))
                newDocument["EmailAddress"] = source.EmailAddress;

            if (!string.IsNullOrEmpty(source.Password))
                newDocument["Password"] = source.Password;

            if (source.RegistrationDate != DateTime.MinValue)
                newDocument["RegistrationDate"] = source.RegistrationDate.ToString();

            if (source.LastLoginDate != DateTime.MinValue)
                newDocument["LastLoginDate"] = source.LastLoginDate.ToString();

            return newDocument;
        }

    }

    public class DocumentToUserConverter : ITypeConverter<Document, User>
    {

        public User Convert(Document source)
        {
            User newUser = new User();

            if (source["_id"] != null)
                newUser.ID = source["_id"].ToString().Trim().Substring(10, 24);

            if (source["UserName"] != null)
                newUser.UserName = source["UserName"].ToString();

            if (source["EmailAddress"] != null)
                newUser.EmailAddress = source["EmailAddress"].ToString();

            if (source["Password"] != null)
                newUser.Password = source["Password"].ToString();

            if (source["RegistrationDate"] != null)
                newUser.RegistrationDate = DateTime.Parse(source["RegistrationDate"].ToString());

            if (source["LastLoginDate"] != null)
                newUser.LastLoginDate = DateTime.Parse(source["LastLoginDate"].ToString());

            return newUser;
        }

    }
}
